#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sqlite3.h>
#include "door.h"
#include "doorinfo.h"
#include "portvictoria.h"

extern struct shipdata_t **ships;
extern int ship_count;
extern struct playerdata_t *player;

int shipyard(void) {
	int i;
	char c;
	int j;
	
	drprintf("\e[2J\e[1;33mYou have %d gold coins.\r\n\r\n", player->dollars);
	
	for (i=0;i<ship_count;i++) {
		drprintf("        \e[1;37m(\e[1;33m%d\e[1;37m) %15s Price: %6d Trade-in: %6d %s\r\n", i+1, ships[i]->name, ships[i]->value, ships[i]->value / 2, (ships[i]->id == player->ship->id ? "(You own this)" : "" ));
	}
	drprintf("\r\n        \e[1;37m(\e[1;33mR\e[1;37m) Return to the docks\r\n");
	drprintf("        \e[1;37m(\e[1;31mQ\e[1;37m) Quit to BBS\r\n\e[0m");
	
	c = drgetc();
	while (c == -1) {
		usleep(100);
		c = drgetc();
	}
	
	switch(tolower(c)) {
			case 'r':
				return 0;
			case 'q':
				return 1;
			default:
				j = c - '0';
				if (j > 0 && j <= i) {
					j--;
					if (player->dollars + (player->ship->value / 2) < ships[j]->value) {
						drprintf("\r\nYou can't afford that!\r\n\r\nPress ENTER to continue...\r\n");
						c = drgetc();
						while (c != '\r' && c != '\n') {
							usleep(100);
							c = drgetc();
						}
						return 0;
					}
					drprintf("\r\nAre you sure you want to trade in your %s and buy a %s?\r\n", player->ship->name, ships[j]->name);
					if (yesno()) {
						player->dollars = player->dollars - (ships[j]->value - (player->ship->value / 2));
						player->ship = ships[j];
						
						drprintf("Congratulations! You're now the proud owner of a shiny new %s.\r\n\r\nPress ENTER to continue...\r\n", player->ship->name);
						
						c = drgetc();
						while (c != '\r' && c != '\n') {
							usleep(100);
							c = drgetc();
						}
					}
					return 0;
				}
				return 0;
	}
}
